/** 
* @Title: MultiThreadShareData.java 
* @Package com.lh.threadtest.t7 
* @Description: TODO
* @author Liu 
* @date 2018年1月16日 下午9:45:37 
* @version V1.0 
*/
package com.lh.threadtest.t7;

/** 
* @ClassName: MultiThreadShareData 
* @Description: 多个线程之间共享数据的方式探讨
* 
* 题目：
* 	设计4个线程，其中两个线程每次对j增加1，另外两个线程对j每次都减少1，写出程序。
* 
* @author Liu
* @date 2018年1月16日 下午9:45:37 
*  
*/
public class MultiThreadShareData2 {
	
	/***
	* @Title: main 
	* @Description: TODO
	* @param @param args
	* @return void
	* @throws 
	*/
	public static void main(String[] args) {
		Business business = new Business();
		
		for(int i = 0; i< 2; i++){
			new Thread(new Inc(business)).start();
			new Thread(new Dec(business)).start();
		}
	}
}

class Inc implements Runnable{
	private Business business;

	public Inc(Business business){
		this.business = business;
	}

	/* (非 Javadoc) 
	* <p>Title: run</p> 
	* <p>Description: </p>  
	* @see java.lang.Runnable#run() 
	*/
	@Override
	public void run() {
		for(int i = 0; i< 5; i++){
			this.business.inc();
		}
	}
	
}

class Dec implements Runnable{
	private Business business;
	
	public Dec(Business business){
		this.business = business;
	}
	
	/* (非 Javadoc) 
	 * <p>Title: run</p> 
	 * <p>Description: </p>  
	 * @see java.lang.Runnable#run() 
	 */
	@Override
	public void run() {
		for(int i = 0; i< 5; i++){
			this.business.dec();
		}
	}
	
}

class Business{
	private int j = 0;
	
	public synchronized void inc(){
		j++;
		System.out.println(Thread.currentThread().getName() + "中 j = " + j);
	}
	
	public synchronized void dec(){
		j--;
		System.out.println(Thread.currentThread().getName() + "中 j = " + j);
	}
}
